<template>
  <div class="home">
    <div class="home-tab">
      <ul class="home-tab-list">
        <li @click="selectTab('notetaking')" :class="{ active: activeTab === 'notetaking' }">
          <span class="iconfont icon-iframetianjia"></span>
          <text><strong style="font-weight: bold;">Notetaking</strong></text>
        </li>
        <li @click="selectTab('curation')" :class="{ active: activeTab === 'curation' }">
          <span class="iconfont icon-iframetianjia"></span>
          <text><strong style="font-weight: bold;">Curation</strong></text>
        </li>
        <li @click="selectTab('summary')" :class="{ active: activeTab === 'summary' }">
          <span class="iconfont icon-iframetianjia"></span>
          <text><strong style="font-weight: bold;">Writing</strong></text>
        </li>
      </ul>
    </div>
    <div class="home-content">
      <div class="left-files-tree">
        <div class="left-files-tree-icos">
          <div class="icos-func">
            <el-icon @click="showCreateFileDialog" class="icon-button"><Plus /></el-icon>
            <el-icon @click="showCreateFolderDialog" class="icon-button"><Folder /></el-icon>
          </div>
          <el-icon><Memo /></el-icon>
        </div>
        <el-tree
          style="height: 100%"
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          class="custom-tree"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="node-content">
                <span v-if="data.isFolder" class="folder-icon">
                  <el-icon><Folder /></el-icon>
                </span>
                <span v-else class="file-icon">
                  <el-icon><Document /></el-icon>
                </span>
                <InlineEdit
                  :model-value="node.label"
                  @rename="(newName) => renameItem(data, newName)"
                >
                  <span class="node-label">{{ node.label }}</span>
                </InlineEdit>
              </span>
              <div class="tree-node-actions">
                <el-icon class="upload-icon" @click.stop="uploadFiles(data)" v-if="data.isFolder"><Upload /></el-icon>
                <el-icon class="delete-icon" @click.stop="confirmDelete(data)"><Delete /></el-icon>
              </div>
            </span>
          </template>
        </el-tree>
        
      </div>
      <div class="left-editor">
        <MdEditor 
          class="md custom-md-editor"  
          v-model="markdownContent" 
          :preview="previewMode"
          :toolbars="toolbars"
          inputBoxWitdh="50%" 
          showPreview="false"
          language="en-US"    
          @change="handleMarkdownChange"
        >
          <template #defToolbars>
            <NormalToolbar title="mark" @onClick="markHandler">
              <template #trigger>
                <svg class="md-editor-icon" aria-hidden="true">
                  <use xlink:href="#icon-mark"></use>
                </svg>
              </template>
            </NormalToolbar>
          </template>
        </MdEditor>
      </div>
      <div class="home-right">
        <div class="home-right-header">
          <div class="summary-paper-btn" @click="summaryPaper">
            <span class="iconfont icon-iframetianjia"></span>
            <div class="summary-text">
              <span>Summary</span>
              <span>This Paper</span>
            </div>
          </div>
          <el-input
            v-model="interInput"
            style="width: 60%; color:#fff"
            size="large"
            placeholder="Enter URL"
            @keyup.enter="onEnterPress"
          />
        </div>
        <div v-if="iframeUrl" class="iframe-container">
          <iframe 
            v-if="!iframeError"
            :key="iframeUrl" 
            :src="iframeUrl" 
            class="iframe" 
            width="100%" 
            frameborder="0" 
            @load="iframeLoaded" 
            @error="handleIframeError"
          ></iframe>
          <div v-else class="error-message">
            <p>{{ iframeErrorMessage }}</p>
            <el-button type="primary" @click="openLinkInNewTab">Open in New Tab</el-button>
          </div>
        </div>
        <div  class="file-preview">
          <img :src="imageSrc" width="80%" v-if="fileType === 'img'" />
          <VueOfficePdf v-if="fileType === 'pdf'" style="width: 80%;" :src="PDFSrc" />
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="Thoth Note Initialization"
      width="500"
      align-center
    >
      <span>Welcome to Thoth Note! To initialize, select your Obsidian directory.</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="filesBtn">
            Select
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <el-dialog
      v-model="showAuthDialog"
      title="Login or Sign Up"
      width="300"
      align-center
    >
      <div class="auth-container">
        <el-form 
          @submit.prevent="handleSubmit" 
          :model="formData"
          :rules="formRules"
          ref="authForm"
        >
          <el-form-item v-if="isSignUp" prop="name">
            <el-input v-model="formData.name" placeholder="Name" />
          </el-form-item>
          <el-form-item prop="email">
            <el-input v-model="formData.email" placeholder="Email" type="email" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formData.password" placeholder="Password" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" style="width: 100%;">
              {{ isSignUp ? 'Sign Up' : 'Login' }}
            </el-button>
          </el-form-item>
        </el-form>
        <el-button @click="toggleAuthMode" type="text">
          {{ isSignUp ? 'Already have an account? Login' : 'Need an account? Sign Up' }}
        </el-button>
        <el-divider>or</el-divider>
        <el-button @click="signInWithGoogle" style="width: 100%;">
          <i class="el-icon-google"></i> Continue with Google
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-model="showNewFileDialog"
      title="Create New Markdown File"
      width="30%"
    >
      <el-input v-model="newFileName" placeholder="Enter file name (without extension)"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewFileDialog = false">Cancel</el-button>
          <el-button type="primary" @click="createNewFile">Create</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Delete confirmation dialog -->
    <el-dialog
      v-model="showDeleteDialog"
      title="Confirm Delete"
      width="30%"
    >
      <p>Are you sure you want to delete {{ itemToDelete?.label }}?</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">Cancel</el-button>
          <el-button type="danger" @click="deleteItem">Delete</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Secondary confirmation for non-empty folders -->
    <el-dialog
      v-model="showSecondaryDeleteDialog"
      title="Warning: Non-empty Folder"
      width="30%"
    >
      <p>This folder is not empty. Are you sure you want to delete it and all its contents?</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSecondaryDeleteDialog = false">Cancel</el-button>
          <el-button type="danger" @click="proceedWithDelete">Delete</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- New Folder Dialog -->
    <el-dialog
      v-model="showNewFolderDialog"
      title="Create New Folder at Root Level"
      width="30%"
    >
      <el-input v-model="newFolderName" placeholder="Enter folder name"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewFolderDialog = false">Cancel</el-button>
          <el-button type="primary" @click="createNewFolder">Create at Root</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup> 
  import { ref, reactive, onMounted, nextTick, watch } from 'vue'
  import { MdEditor, NormalToolbar } from 'md-editor-v3';
  import 'md-editor-v3/lib/style.css';
  // PDF Preview plugin
  import VueOfficePdf from '@vue-office/pdf'
  import { initializeApp } from 'firebase/app'
  import { 
    getAuth, 
    onAuthStateChanged, 
    signInWithEmailAndPassword, 
    createUserWithEmailAndPassword,
    GoogleAuthProvider,
    signInWithPopup
  } from 'firebase/auth'
  import { getFirestore, doc, setDoc, getDoc, collection, getDocs, updateDoc, deleteDoc, writeBatch } from 'firebase/firestore'
  import { ElInput, ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Folder, Document, Delete, Upload } from '@element-plus/icons-vue'
  import InlineEdit from '@/components/InlineEdit.vue';
  import debounce from 'lodash/debounce'

  const text = ref('# Hello Editor edfwefdwef');

  const defaultProps = {
    children: 'children',
    label: 'label',
  }

  // let showBtn = ref(false)

  const treeData = ref([])
  const currentFolderPath = ref('')
  const markdownContent = ref('')
  const currentFilePath = ref('')
  let previewMode = ref(false)
  let interInput = ref('')
  let iframeUrl = ref('')
  let dialogVisible = ref(true)
  // let folderInput = ref(null)
  let imageSrc = ref('')
  let fileType = ref('')
  let PDFSrc = ref('')
  let activeTab = ref('notetaking')
  let iframeError = ref(false)
  let iframeErrorMessage = ref('')
  const showAuthDialog = ref(false)
  const user = ref(null)
  const isSignUp = ref(false)
  const authForm = ref(null)
  const showNewFileDialog = ref(false)
  const newFileName = ref('')
  const showDeleteDialog = ref(false)
  const showSecondaryDeleteDialog = ref(false)
  const itemToDelete = ref(null)
  const showNewFolderDialog = ref(false)
  const newFolderName = ref('')

  const formData = reactive({
    name: '',
    email: '',
    password: ''
  })

  const emailError = ref('')
  const passwordError = ref('')

  const formRules = {
    name: [
      { required: true, message: 'Please input your name', trigger: 'blur' }
    ],
    email: [
      { required: true, message: 'Please input your email', trigger: 'blur' },
      { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
    ],
    password: [
      { required: true, message: 'Please input your password', trigger: 'blur' },
      { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' }
    ]
  }

  const selectTab = (tab) => {
    activeTab.value = tab
  }

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "AIzaSyCfCIi9bpLEzZCgNrNGZAsXewi4hUWzeIw",
    authDomain: "thoth-notes.firebaseapp.com",
    projectId: "thoth-notes",
    storageBucket: "thoth-notes.appspot.com",
    messagingSenderId: "802857257252",
    appId: "1:802857257252:web:a014337b5682443a9f4bb1",
    measurementId: "G-0DQH0XT1E0"
  };

  onMounted(() => {
    const app = initializeApp(firebaseConfig)
    const auth = getAuth(app)
    const db = getFirestore(app)

    onAuthStateChanged(auth, (currentUser) => {
      if (currentUser) {
        user.value = currentUser
        showAuthDialog.value = false
        fetchUserFolders(currentUser.uid)
      } else {
        showAuthDialog.value = true
        treeData.value = []
      }
    })
  })

  async function fetchUserFolders(userId) {
    const db = getFirestore()
    const userDocRef = doc(db, 'users', userId)

    try {
      const docSnap = await getDoc(userDocRef)
      if (docSnap.exists()) {
        const userData = docSnap.data()
        treeData.value = await convertToTreeData(userData.folders || {}, userId)
      } else {
        console.log('No user data found')
        treeData.value = []
      }
    } catch (error) {
      console.error('Error fetching user folders:', error)
      ElMessage.error('Failed to fetch folders')
    }
  }

  async function convertToTreeData(folders, userId, parentPath = '', level = 0) {
    const result = []

    for (const [name, content] of Object.entries(folders)) {
      const currentPath = parentPath ? `${parentPath}/${name}` : name
      const node = {
        label: name,
        path: currentPath,
        isFolder: true,
        children: [],
      }

      if (typeof content === 'object' && content !== null && level < 1) {
        // This is a folder and we're not at the second level yet
        node.children = await convertToTreeData(content, userId, currentPath, level + 1)
      } else if (typeof content === 'object' && content !== null) {
        // This is a folder at the second level, don't process children but indicate it has children
        node.children = [{ label: '...', isPlaceholder: true }]
      }

      result.push(node)
    }

    // Fetch files for the current level
    if (parentPath && level < 2) {
      const db = getFirestore()
      const folderRef = collection(db, 'users', userId, parentPath)
      try {
        const querySnapshot = await getDocs(folderRef)
        querySnapshot.forEach((doc) => {
          if (!result.some(item => item.label === doc.id)) {
            result.push({
              label: doc.id,
              path: `${parentPath}/${doc.id}`,
              isFolder: false,
            })
          }
        })
      } catch (error) {
        console.error('Error fetching files:', error)
      }
    }

    return result
  }

  function toggleAuthMode() {
    isSignUp.value = !isSignUp.value
    if (authForm.value) {
      authForm.value.resetFields()
    }
  }

  async function handleSubmit() {
    if (!authForm.value) return
    
    try {
      await authForm.value.validate()
      const auth = getAuth()
      let userCredential
      if (isSignUp.value) {
        userCredential = await createUserWithEmailAndPassword(auth, formData.email, formData.password)
        await createUserFolders(userCredential.user.uid)
      } else {
        userCredential = await signInWithEmailAndPassword(auth, formData.email, formData.password)
      }
      // Handle successful authentication
      ElMessage.success(isSignUp.value ? 'Sign up successful!' : 'Login successful!')
    } catch (error) {
      console.error('Authentication error:', error)
      handleAuthError(error)
    }
  }

  function handleAuthError(error) {
    let errorMessage = 'An error occurred. Please try again.'
    
    switch (error.code) {
      case 'auth/email-already-in-use':
        errorMessage = 'This email is already in use. Please use a different email or try logging in.'
        break
      case 'auth/invalid-email':
        errorMessage = 'Invalid email address. Please check your email and try again.'
        break
      case 'auth/weak-password':
        errorMessage = 'Password is too weak. Please use a stronger password.'
        break
      case 'auth/user-not-found':
      case 'auth/wrong-password':
        errorMessage = 'Invalid email or password. Please check your credentials and try again.'
        break
      case 'auth/too-many-requests':
        errorMessage = 'Too many unsuccessful attempts. Please try again later.'
        break
      case 'auth/network-request-failed':
        errorMessage = 'Network error. Please check your internet connection and try again.'
        break
      // Add more cases as needed
    }

    ElMessage.error(errorMessage)
  }

  async function createUserFolders(userId) {
    const db = getFirestore()
    const userFolderRef = doc(db, 'users', userId)
    
    const folderStructure = {
      Attachments: {},
      Insights: {},
      Files: {},
      Notes: {},
      Writings: {}
    }

    try {
      await setDoc(userFolderRef, { folders: folderStructure })
      console.log('User folders created successfully')
    } catch (error) {
      console.error('Error creating user folders:', error)
    }
  }

  async function signInWithGoogle() {
    const auth = getAuth()
    const provider = new GoogleAuthProvider()
    try {
      const result = await signInWithPopup(auth, provider)
      await createUserFolders(result.user.uid)
      ElMessage.success('Google sign-in successful!')
    } catch (error) {
      console.error('Google sign-in error:', error)
      handleAuthError(error)
    }
  }

  function initDialog() {
    let obsDianPath = window.localStorage.getItem('obsDianPath')
    if(!obsDianPath) {
    } else {
    }
  }

  async function selectDirectory() {
    const handle = await window.showDirectoryPicker();
    processHandle()
    for await (const entry of handle.values()) {
      console.log(entry);
      processHandle(entry)
    }
  }
  
  async function readFile(handle) {
    return new Promise(async (resolve, reject) => {
      const file = await handle.getFile()
      const fileReader = new FileReader()
      fileReader.readAsText(file)
      fileReader.onload = e => {
        resolve(e.target.result)
      }
    })
  }

  const file2Text = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => resolve(e.target.result);
      reader.onerror = reject;
      reader.readAsText(file);
    });
  };

  function createAndDownloadFile(filename, content) {
    var blob = new Blob([content], { type: 'text/plain' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  async function createDirectory(directoryPath) {
  }

  function filesBtn() {
    dialogVisible.value = false
    selectDirectory()
  }

  async function handleNodeClick(data) {
    if (data.isFolder) {
      currentFolderPath.value = data.path
      if (data.children.length === 1 && data.children[0].isPlaceholder) {
        // This folder hasn't been fully loaded yet
        await loadFolderContents(data)
      }
    } else if (data.path.endsWith('.md')) {
      await openMarkdownFile(data.path)
    }
  }

  async function loadFolderContents(folderNode) {
    const db = getFirestore()
    const userId = user.value.uid
    const userDocRef = doc(db, 'users', userId)

    try {
      const docSnap = await getDoc(userDocRef)
      if (docSnap.exists()) {
        const userData = docSnap.data()
        let folders = userData.folders || {}
        
        // Navigate to the correct nested folder
        const pathParts = folderNode.path.split('/')
        for (const part of pathParts) {
          folders = folders[part] || {}
        }

        // Load the contents of this folder
        folderNode.children = await convertToTreeData(folders, userId, folderNode.path, 1)
      }
    } catch (error) {
      console.error('Error loading folder contents:', error)
      ElMessage.error('Failed to load folder contents')
    }
  }

  async function openMarkdownFile(filePath) {
    const db = getFirestore()
    const userId = user.value.uid
    const fileRef = doc(db, 'users', userId, filePath)

    try {
      const docSnap = await getDoc(fileRef)
      if (docSnap.exists()) {
        markdownContent.value = docSnap.data().content
        currentFilePath.value = filePath // Store the current file path
      } else {
        console.log('No such document!')
      }
    } catch (error) {
      console.error('Error opening markdown file:', error)
    }
  }

  async function processHandle(handle) {
    console.log('')
    if (handle.kind === 'file') {
      treeData.value.push(handle)
    } else {
       handle.children = []
      const iter = await handle.entries()
      console.log('iter',iter)
      for await (const entry of iter) {
        await processHandle(entry[1])
        handle.children.push(entry[1])
      }
       treeData.value.push(handle)
    }
  }

  const onEnterPress = () => {
    let url = interInput.value.trim()
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'https://' + url
    }
    iframeUrl.value = url
    iframeError.value = false
    iframeErrorMessage.value = ''
    console.log('iframeUrl',iframeUrl.value)
  }

  const handleIframeError = () => {
    iframeError.value = true
    iframeErrorMessage.value = 'This website cannot be displayed in an iframe. You can try opening it in a new tab.'
  }

  const openLinkInNewTab = () => {
    window.open(iframeUrl.value, '_blank')
  }

  const mdCheckBtn = () => {
    previewMode.value = !previewMode.value
  }

  const summaryPaper = () => {
    console.log('Summarizing paper...');
  }

  const iframeLoaded = () => {
    iframeErrorMessage.value = ''
  }

  function showCreateFileDialog() {
    if (!currentFolderPath.value) {
      ElMessage.warning('Please select a folder first')
      return
    }
    showNewFileDialog.value = true
  }

  async function createNewFile() {
    if (!newFileName.value.trim()) {
      ElMessage.warning('File name cannot be empty')
      return
    }

    const db = getFirestore()
    const userId = user.value.uid
    const filePath = `${currentFolderPath.value}/${newFileName.value}.md`
    const fileRef = doc(db, 'users', userId, filePath)

    try {
      await setDoc(fileRef, { content: '' })
      ElMessage.success('File created successfully')
      showNewFileDialog.value = false
      newFileName.value = ''
      await updateFolderStructure(filePath)
      await fetchUserFolders(userId)
    } catch (error) {
      console.error('Error creating file:', error)
      ElMessage.error('Failed to create file')
    }
  }

  async function updateFolderStructure(filePath) {
    const db = getFirestore()
    const userId = user.value.uid
    const userDocRef = doc(db, 'users', userId)

    try {
      const docSnap = await getDoc(userDocRef)
      if (docSnap.exists()) {
        const userData = docSnap.data()
        const folders = userData.folders || {}
        
        const pathParts = filePath.split('/')
        let currentLevel = folders

        for (let i = 0; i < pathParts.length - 1; i++) {
          if (!currentLevel[pathParts[i]]) {
            currentLevel[pathParts[i]] = {}
          }
          currentLevel = currentLevel[pathParts[i]]
        }

        await updateDoc(userDocRef, { folders })
      }
    } catch (error) {
      console.error('Error updating folder structure:', error)
    }
  }

  async function renameItem(item, newName) {
    if (item.label === newName) return;

    const db = getFirestore();
    const userId = user.value.uid;
    const oldPath = item.path;
    const newPath = oldPath.substring(0, oldPath.lastIndexOf('/') + 1) + newName;

    try {
      if (item.isFolder) {
        await renameFolder(oldPath, newPath);
      } else {
        await renameFileFromFirebase(oldPath, newPath);
      }

      item.label = newName;
      item.path = newPath;
      ElMessage.success('Renamed successfully');
      
      // Refresh the tree data
      await fetchUserFolders(userId);
    } catch (error) {
      console.error('Error renaming item:', error);
      ElMessage.error('Failed to rename item');
    }
  }

  async function renameFolder(oldPath, newPath) {
    const db = getFirestore();
    const userId = user.value.uid;
    const userDocRef = doc(db, 'users', userId);

    const batch = writeBatch(db);  // Create a batch using writeBatch

    // Update folder structure
    const docSnap = await getDoc(userDocRef);
    if (docSnap.exists()) {
      const userData = docSnap.data();
      const folders = userData.folders || {};
      
      // Helper function to update nested path
      function updatePath(obj, oldPath, newPath) {
        const parts = oldPath.split('/');
        const newParts = newPath.split('/');
        let current = obj;
        for (let i = 0; i < parts.length - 1; i++) {
          if (current[parts[i]]) {
            current = current[parts[i]];
          } else {
            return; // Path doesn't exist
          }
        }
        if (current[parts[parts.length - 1]]) {
          current[newParts[newParts.length - 1]] = current[parts[parts.length - 1]];
          delete current[parts[parts.length - 1]];
        }
      }

      updatePath(folders, oldPath, newPath);
      batch.update(userDocRef, { folders });
    }

    // Rename all nested files and folders
    const oldFolderRef = collection(db, 'users', userId, oldPath);
    const querySnapshot = await getDocs(oldFolderRef);

    querySnapshot.forEach((doc) => {
      const oldItemPath = `${oldPath}/${doc.id}`;
      const newItemPath = `${newPath}/${doc.id}`;
      const newItemRef = doc(db, 'users', userId, newItemPath);
      batch.set(newItemRef, doc.data());
      batch.delete(doc.ref);
    });

    await batch.commit();
  }

  async function renameFileFromFirebase(oldPath, newPath) {
    const db = getFirestore();
    const userId = user.value.uid;
    const oldFileRef = doc(db, 'users', userId, oldPath);
    const newFileRef = doc(db, 'users', userId, newPath);

    const docSnap = await getDoc(oldFileRef);
    if (docSnap.exists()) {
      await setDoc(newFileRef, docSnap.data());
      await deleteDoc(oldFileRef);
    }
  }

  function confirmDelete(item) {
    itemToDelete.value = item
    showDeleteDialog.value = true
  }

  async function deleteItem() {
    if (itemToDelete.value.isFolder) {
      const hasContents = await checkFolderContents(itemToDelete.value.path)
      if (hasContents) {
        showDeleteDialog.value = false
        showSecondaryDeleteDialog.value = true
        return
      }
    }
    proceedWithDelete()
  }

  async function proceedWithDelete() {
    try {
      if (itemToDelete.value.isFolder) {
        await deleteFolder(itemToDelete.value.path)
      } else {
        await deleteFileFromFirebase(itemToDelete.value.path)
      }
      ElMessage.success('Item deleted successfully')
      await fetchUserFolders(user.value.uid)
    } catch (error) {
      console.error('Error deleting item:', error)
      ElMessage.error('Failed to delete item')
    } finally {
      showDeleteDialog.value = false
      showSecondaryDeleteDialog.value = false
      itemToDelete.value = null
    }
  }

  async function checkFolderContents(folderPath) {
    const db = getFirestore()
    const userId = user.value.uid
    const folderRef = collection(db, 'users', userId, folderPath)
    const querySnapshot = await getDocs(folderRef)
    return !querySnapshot.empty
  }

  async function deleteFolder(folderPath) {
    const db = getFirestore()
    const userId = user.value.uid
    const batch = writeBatch(db)

    // Delete all files in the folder
    const folderRef = collection(db, 'users', userId, folderPath)
    const querySnapshot = await getDocs(folderRef)
    querySnapshot.forEach((doc) => {
      batch.delete(doc.ref)
    })

    // Update folder structure
    const userDocRef = doc(db, 'users', userId)
    const userDoc = await getDoc(userDocRef)
    if (userDoc.exists()) {
      const userData = userDoc.data()
      const folders = userData.folders || {}
      const pathParts = folderPath.split('/')
      let current = folders
      for (let i = 0; i < pathParts.length - 1; i++) {
        current = current[pathParts[i]]
      }
      delete current[pathParts[pathParts.length - 1]]
      batch.update(userDocRef, { folders })
    }

    await batch.commit()
  }

  async function deleteFileFromFirebase(filePath) {
    const db = getFirestore()
    const userId = user.value.uid
    const fileRef = doc(db, 'users', userId, filePath)
    await deleteDoc(fileRef)

    // Update folder structure
    const userDocRef = doc(db, 'users', userId)
    const userDoc = await getDoc(userDocRef)
    if (userDoc.exists()) {
      const userData = userDoc.data()
      const folders = userData.folders || {}
      const pathParts = filePath.split('/')
      let current = folders
      for (let i = 0; i < pathParts.length - 1; i++) {
        current = current[pathParts[i]]
      }
      delete current[pathParts[pathParts.length - 1]]
      await updateDoc(userDocRef, { folders })
    }
  }

  function showCreateFolderDialog() {
    showNewFolderDialog.value = true
  }

  async function createNewFolder() {
    if (!newFolderName.value.trim()) {
      ElMessage.warning('Folder name cannot be empty')
      return
    }

    const db = getFirestore()
    const userId = user.value.uid
    const folderPath = [newFolderName.value] // This creates the folder at the root level
    const userDocRef = doc(db, 'users', userId)

    try {
      const docSnap = await getDoc(userDocRef)
      if (docSnap.exists()) {
        const userData = docSnap.data()
        let folders = userData.folders || {}
        
        // Check if the folder already exists at the root level
        if (folders[newFolderName.value]) {
          ElMessage.warning('A folder with this name already exists')
          return
        }

        // Create the new folder at the root level
        folders[newFolderName.value] = {}

        await updateDoc(userDocRef, { folders })
        ElMessage.success('Folder created successfully')
        showNewFolderDialog.value = false
        newFolderName.value = ''
        
        // Refresh the folder list
        await fetchUserFolders(userId)
      }
    } catch (error) {
      console.error('Error creating folder:', error)
      ElMessage.error('Failed to create folder')
    }
  }

  const saveMarkdownContent = debounce(async () => {
    if (!currentFilePath.value) return

    const db = getFirestore()
    const userId = user.value.uid
    const fileRef = doc(db, 'users', userId, currentFilePath.value)

    try {
      await setDoc(fileRef, { content: markdownContent.value }, { merge: true })
      console.log('Document successfully saved!')
    } catch (error) {
      console.error('Error saving document:', error)
    }
  }, 1000) // Debounce for 1 second

  function handleMarkdownChange(content) {
    markdownContent.value = content
    saveMarkdownContent()
  }

  const toolbars = ['bold', 'underline', 'italic', 'strikeThrough', '-', 'title', 'sub', 'sup', 'quote', 'unorderedList', 
  '-', 'link', 'image', 'table', 'katex', '-', 'revoke', 'next', '=', 'previewOnly', 'catalog']

  // unused toolbar functions: ['pageFullscreen', 'fullscreen', 'preview', 'orderedList', 'task', 'codeRow', 'code', ]

  const markHandler = () => {
    console.log('Mark toolbar clicked!');
    // Add your custom mark functionality here
  };

  async function uploadFiles(folder) {
    const input = document.createElement('input');
    input.type = 'file';
    input.multiple = true;
    input.accept = '.md';
    
    input.onchange = async (e) => {
      const files = Array.from(e.target.files);
      for (const file of files) {
        const content = await readFileContent(file);
        await uploadFile(file, folder.path, content);
      }
      await fetchUserFolders(user.value.uid);
    };
    
    input.click();
  }

  async function uploadFile(file, folderPath, content) {
    const db = getFirestore();
    const userId = user.value.uid;
    const filePath = `${folderPath}/${file.name}`;
    const fileRef = doc(db, 'users', userId, filePath);

    try {
      await setDoc(fileRef, { content });
      await updateFolderStructure(filePath);
      ElMessage.success(`File ${file.name} uploaded successfully`);
    } catch (error) {
      console.error('Error uploading file:', error);
      ElMessage.error(`Failed to upload ${file.name}`);
    }
  }

  function readFileContent(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (event) => resolve(event.target.result);
      reader.onerror = (error) => reject(error);
      reader.readAsText(file);
    });
  }
</script>
<style>
.el-tree {
  background: #8267ad;
  color: white;
}
.el-tree-node__content {
  color: white;
}
.el-tree-node__content:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.el-tree-node.is-current > .el-tree-node__content {
  background-color: #635A73 !important;
}

/* New styles for larger text */
.custom-tree {
  font-size: 16px; /* Adjust this value as needed */
}
.custom-tree .el-tree-node__content {
  height: 36px; /* Increase height to accommodate larger text */
  line-height: 36px; /* Align text vertically */
}

.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.folder-icon, .file-icon {
  margin-right: 8px;
}

.el-tree-node__content {
  height: 36px;
}

.el-tree-node__expand-icon {
  font-size: 16px;
}

.el-tree-node__expand-icon.is-leaf {
  visibility: hidden;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  min-width: 0;
}

.node-content {
  display: flex;
  align-items: center;
  min-width: 0;
  flex: 1;
  margin-right: 10px;
}

.node-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tree-node-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.upload-icon,
.delete-icon {
  font-size: 20px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-icon {
  color: #ffffff;
  margin-right: 5px;
}

.delete-icon {
  color: #f56c6c;
}

.custom-tree-node:hover .upload-icon,
.custom-tree-node:hover .delete-icon {
  opacity: 1;
}
</style>
<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  
}
.home-tab {
  width: 100%;
  height: 60px;
  border-bottom: 1px solid #ccc;
  display: flex;
  justify-content: center;
  background: #8267ad;
  .home-tab-list {
    list-style: none;
    display: flex;
    align-items: center;
    & li {
      cursor: pointer;
      list-style: none;
      margin: 0  15px;
      color: #fff;
      position: relative;
      
      &.active::after {
        content: '';
        position: absolute;
        bottom: -15px;
        left: 50%;
        transform: translateX(-50%);
        width: 0;
        height: 0;
        border-left: 20px solid transparent;
        border-right: 20px solid transparent;
        border-bottom: 10px solid white;
      }
      
      & span {
        padding-right: 8px;
        font-size: 22px;
      }
    }
  }
}
.home-content {
  width: 100%;
  height: calc( 100% - 80px );
  display: flex;
  .left-files-tree {
    width: 340px;
    height: 100%;
    border-right: 1px solid #ccc;
    padding: 0 10px;
    background: #8267ad;
    color: white;
    overflow-y: auto;
    display: flex;
    flex-direction: column;

    .left-files-tree-icos {
      height: 60px;
      border-bottom: 2px solid #fff;
      font-size: 20px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
      flex-shrink: 0;

      .icos-func {
        margin-right: 28%;
        display: flex;
        align-items: center;
        justify-content: center;
        .el-icon {
          margin: 0 10px;
          cursor: pointer;
        }
      }
    }

    .el-tree {
      flex-grow: 1;
      overflow-y: auto;
      margin-top: 15px;
    }
  }
  .left-editor {
    width: 45%;
    height: 100%;
    overflow-y: auto;
    border-right: 1px solid #ccc;
    display: flex;
    flex-direction: column;
  }
  .home-right {
    width: 50%;
    height: 100%;
  }
}
.md {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.home-right-header {
  display: flex;
  align-items: center;
  margin-left: 20px;
  padding-top: 10px;
}
.summary-paper-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px;
  margin-right: 20px;
  
  .iconfont {
    font-size: 24px;
    margin-right: 10px;
  }

  .summary-text {
    display: flex;
    flex-direction: column;
    
    span {
      line-height: 1.2;
    }
  }
}
.iframe {
  height: 100%;
  background: #8267ad;
}
.file-preview {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.imgPer {
  width: 80%;
  margin: 0 auto;
}
.iframe-container {
  position: relative;
  width: 100%;
  height: calc(100% - 80px);
  background: #8267ad;
  margin-top: 10px;
}
.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
  z-index: 1;
}
.auth-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-form {
  width: 100%;
}

.el-divider {
  margin: 20px 0;
}

.icos-func {
  display: flex;
  gap: 10px;
  .icon-button {
    font-size: 24px;
    cursor: pointer;
    color: white;
    &:hover {
      color: #e6e6e6;
    }
  }
}

/* Custom styles for MdEditor */
.custom-md-editor .md-editor-toolbar {
  flex-wrap: wrap;
  justify-content: flex-start;
  height: auto !important;
  min-height: 40px;
  padding: 5px;
}

.custom-md-editor .md-editor-toolbar .md-editor-toolbar-item {
  margin-bottom: 5px;
}

.custom-md-editor .md-editor-input {
  top: auto !important;
  height: calc(100% - 50px) !important;
}

/* Adjust the content area to accommodate the multi-line toolbar */
.custom-md-editor .md-editor-content {
  height: calc(100% - 50px) !important;
}

/* Add this to ensure the custom toolbar icon is visible */
.md-editor-icon {
  width: 20px;
  height: 20px;
}
</style>

